<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #big {
        width: 400px;
        height: 400px;
        margin: 200px 0 0 100px;
        border: solid;
        position: relative;
      }

      #small {
        width: 100px;
        height: 100px;
        background-color: rgb(117, 110, 101);
        position: absolute;
        transition: 200ms;
      }
    </style>
  </head>
  <body>
    <div id="big">
      <div id="small" style="left: 0; top: 0"></div>
    </div>
    <script>
      const big = document.getElementById("big");
      const small = document.getElementById("small");
      const {
        x: bigX,
        y: bigY,
        right: bigRight,
        bottom: bigBottom,
      } = big.getBoundingClientRect();

      big.onclick = function (e) {
        small.style.left = e.clientX - bigX - small.offsetWidth / 2 + "px";

        small.style.top = e.clientY - bigY - small.offsetHeight / 2 + "px";
      };

      small.addEventListener("transitionend", () => {
        // 判断是否越界
        const {
          x: smallX,
          y: smallY,
          right: smallRight,
          bottom: smallBottom,
        } = small.getBoundingClientRect();

        if (smallX < bigX) {
          small.style.right = "";
          small.style.left = "0px";
        }

        if (smallRight > bigRight) {
          small.style.left = "";
          small.style.right = "0px";
        }

        if (smallY < bigY) {
          small.style.bottom = "";
          small.style.top = "0px";
        }

        if (smallBottom > bigBottom) {
          small.style.top = "";
          small.style.bottom = "0px";
        }
      });
    </script>
  </body>
</html>
